package com.zdgk.core.licence;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class LicenceUtil {

    public static final String static_privateKey ="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJxeiIqC3Ro5etqaXwPbPTJNr8Gb9pN6FNSEDwCRN1JmPsrAKA+IH8mN87lWzQK+fPFwXTERosIjuFYYVG5ev3XX/AsDmT+ictbmMSDYweXtOIPAp3bPmZayOdj4Tuua67j7ZK3iTDyNv9teiNk6RGs8TcMoNiTVtihA3ArWVmr7AgMBAAECgYAFIidaYLxweXWaipnW7xIdviYodX3NTqMzbNhvPNUzm86w6kkGZYIhpErdiUd2sRk59eXhUAJnXDPXg7n1259uagBaEulFixdzM1sm2aIYeu+4+XQ0Nwornk6jiWiQp+MKUxQ0jOjfNGFlVhqALfHqArbV92KCNDKbeF11eejw9QJBAKBN28vrIbwtuC4GTReMjt/bFjb54ENnUde0tEbeIOdYX09SI2v/pl0TIKmqrs4XmPvYvB+WOU+fWbXpiokiPo8CQQD5t1ZkcALYpZVfTT/R/fAvMUteG5I8MQAzbp0pXfv3u03/TNQ4YDS1v9xCx2fTgQJ8U2Rpe55WGbO269tXkMLVAkEAjCvImATgmMV5mXUVEBRuEjxmrmfMu+OqYu21/YnaR7C0lo2CP7tp41UIaJPBCqEDuqSHyy72qjLypOizpLn27QJAIe9CND/sgxhtZhgPVjAWFbOzNES26KsYBeVAQkDdXtr7THhaVpbsUs6R1hlXCKz9c3u5p4P/DmBLxc3jbtDjSQJAOdtn5g7LK0e84LEu0UwOxYtFztKlFmb6U/9sJn+4Pu53UVDlVZHAAkVYaIvsNuoyDPi4ajlvSY0vqGYvTr0Kkw==";
    public static final String static_publicKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcXoiKgt0aOXraml8D2z0yTa/Bm/aTehTUhA8AkTdSZj7KwCgPiB/JjfO5Vs0CvnzxcF0xEaLCI7hWGFRuXr911/wLA5k/onLW5jEg2MHl7TiDwKd2z5mWsjnY+E7rmuu4+2St4kw8jb/bXojZOkRrPE3DKDYk1bYoQNwK1lZq+wIDAQAB";
//    public static void main(String[] args) throws InterruptedException {
//        String machineCode = createMachineCode();
//        System.out.println("机器码");
//        System.out.println(machineCode);
//        String licence = createLicence(machineCode, static_publicKey, 5000);
//        System.out.println("授权码");
//        System.out.println(licence);
//        for (int i = 0; i < 10; i++) {
//            CheckWrapper checkWrapper = licenceCheck(machineCode, "iXGqpxEfxH7SZQ69n58hRkKHj+xW7dIYhl2ym4YBSftrCVtAC9lR4WXF5P/v3/OgWAv1RbXxpMG3U+6k4o+hwoHGGIPwSMgauWuta39BkTCGYopxPelx5Xd5BdBMG1ggwecjci1TA8fTFH5Atd3APeOIZaHOePhT/Mv1IR9AMCmTVrtbN0J02d8c+vNCYVlVcHna0lGPkrXPQ62W8rFd6LDAyusWhNKWQnfMJTxjCWrFGjs0uStxSleVYXkPWddSgdtbSq5JHGE0SdDI9D+71pvEVlWOnTyaOOXzFtP+ppVraXuVftanbomdLgyb88o/MBp/HCuqN878yBRNIn+SLx/qA5VhEG+SvKo2TuyhcaYeFlbEBuj5AW3v3asObPIhmUGYKJP1jlEUxL9Z9u32LeD/84cu5I0MStPAgXCrMFy5AtMgIhVOi1DTRovwAhcqnA/RmB1zJDocroiyW4ItGLQvDSLjxxllh2/d8CaRt9QrYCkwrcnwCdFc1P+tpV3PQwk3cdRpD1Eh9G07mKh+YBLJJ3s906mPuoc4rkxA8Gf0FpTQl7im0boiar+O2K77qZscUMbVLg8JpGknwHJgcTtPU31kzD0PomhsonMWvsNcmCn3ygWqR8UhEY+Crx+nFckLfPQXjYRXeRHi7xwZVIgPro4S0jV1z9O8jTGB92U=", static_privateKey);
//            System.out.println(checkWrapper);
//            Thread.sleep(1000);
//        }
//    }

    /**
     * @description 生成机器码（申请码）
     * @author qiji
     * @date 2022/8/1 16:58
     */
    public static String createMachineCode() {
        try {
            return MachineCodeUtil.createMachineCode();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param machineCode 机器申请码
     * @param publicKey  公钥
     * @param licenceTime 授权时间（毫秒）
     * @description 生成授权码
     * @author qiji
     * @date 2022/8/1 16:04
     */
    public static String createLicence(String machineCode, String publicKey, Integer licenceTime) {
        JSONObject jsonObject = JSONUtil.parseObj(new String(Base64.getDecoder().decode(machineCode)));
        jsonObject.put("applyTime", System.currentTimeMillis());
        if(licenceTime<0){
            jsonObject.put("expireTime", licenceTime);
        }else {
            jsonObject.put("expireTime", jsonObject.getLong("applyTime") + licenceTime);
        }
        String licence = "生成失败";
        try {
            licence = RSA2Utils.publicKeyEncrypt(Base64.getEncoder().encodeToString(jsonObject.toString().getBytes(StandardCharsets.UTF_8)), publicKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return licence;
    }


    /**
     * @description 获取许可证是否有效以及信息
     * @author qiji
     * @date 2022/8/1 17:00
     */
    public static CheckWrapper licenceCheck(String machineCode, String licence, String privateKey) {
        CheckWrapper checkWrapper = new CheckWrapper();
        checkWrapper.setCheck(true);
        checkWrapper.setMsg("许可生效中");
        try {
            String jm = RSA2Utils.privateKeyDecrypt(licence, privateKey);
            String licenceLsonStr = new String(Base64.getDecoder().decode(jm), StandardCharsets.UTF_8);
            String machineCodeLsonStr = new String(Base64.getDecoder().decode(machineCode), StandardCharsets.UTF_8);
            JSONObject licenceJsonObject = JSONUtil.parseObj(licenceLsonStr);
            JSONObject machineCodeJsonObject =  JSONUtil.parseObj(machineCodeLsonStr);
            checkWrapper.setApplyTime(licenceJsonObject.getLong("applyTime"));
            checkWrapper.setExpireTime(licenceJsonObject.getLong("expireTime"));
//            if ((!machineCodeJsonObject.getStr("cpu").equals(licenceJsonObject.getStr("cpu")))
//                    || (!machineCodeJsonObject.getStr("mac").equals(licenceJsonObject.getStr("mac")))
//                    || (!machineCodeJsonObject.getStr("path").equals(licenceJsonObject.getStr("path")))
//            )
            if ((!machineCodeJsonObject.getStr("cpu").equals(licenceJsonObject.getStr("cpu")))
                    || (!machineCodeJsonObject.getStr("mac").equals(licenceJsonObject.getStr("mac")))
            )
            {
                checkWrapper.setCheck(false);
                checkWrapper.setMsg("无效的许可证");
                return checkWrapper;
            }

            if (licenceJsonObject.getLong("expireTime") >= 0) {//期限许可
                if (System.currentTimeMillis() < licenceJsonObject.getLong("expireTime")) {
                    checkWrapper.setCheck(true);
                } else {
                    checkWrapper.setCheck(false);
                    checkWrapper.setMsg("许可证已过期");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            checkWrapper.setCheck(false);
            checkWrapper.setMsg("错误的许可证");
        }

        return checkWrapper;
    }

}
